var express = require('express');
var router = express.Router();
var exec = require("child_process").exec;
const PATH = require('path')
const giteeSettings = require('../config/gitee.json')

var repositories = giteeSettings.repositories;
var baseDir = giteeSettings.baseDir;

router.get('/', function (req, res, next) {
    res.send('Git Hook received!');
});

router.post('/', function (req, res, next) {
    var hook = req.body;
    var hookName = req.body.hook_name;
    if ('push_hooks' !== hookName) {
        res.json(500, {message: 'Only push_hooks support'});
        return;
    }
    var path = hook.repository.path;
    var url = hook.repository.url;
    var password = hook.password;

    var repositorySetting = repositories[path];
    if (!repositorySetting) {
        res.json(500, {message: `Don't support repository of path[${path}], url[${url}]!`});
        return;
    }

    var passwordConfig = repositorySetting.password || path;
    if (passwordConfig !== password) {
        res.json(500, {message: `Password not match repository's password setting of path[${path}], url[${url}]!`});
        return;
    }

    var dir = repositorySetting.dir || baseDir + "/" + path;
    var branch = repositorySetting.branch || 'master';
    var hookBranch = hook.ref.substring('refs/heads/'.length)
    if (hookBranch !== branch) {
        res.json(200, {message: 'Git Hook received!'});
        console.log(`Ignore hookBranch[${hookBranch}] to branch[${branch}] of repository[${url}]`);
        return;
    }
    var deployShPath = PATH.resolve(__dirname, '../deploy.sh');

    console.log(`Try to deploy[${deployShPath}] repository in dir[${dir}], url[${url}], branch[${branch}]`);
    exec(`sh ${deployShPath} ${dir} ${url} ${branch}`, function (error, stdout, stderr) {
        console.log(error, stdout, stderr);
    });
    console.log(req.body);
    res.json(200, {message: 'Git Hook received!'});
});

module.exports = router;
